package net.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Socket Server
 * 
 * @author zhang-hc
 *
 */
public class Main {

	static ServerSocket serverSocket;
	static Socket socket;
	/**
	 * 指定端口号
	 */
	static final int port = 8080;

	public static void main(String[] args) {
		try {
			serverSocket = new ServerSocket(port);
			while (true) {
				// 等待请求，此方法会阻塞
				socket = serverSocket.accept();
				// 用线程处理每一个链接
				new Thread(new SocketTask(socket)).start();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				serverSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

class SocketTask implements Runnable {
	private Socket socket;
	BufferedReader reader = null;
	PrintWriter writer = null;

	public SocketTask(Socket socket) {
		// TODO Auto-generated constructor stub
		this.socket = socket;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			// 用于接收请求
			reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			// 用于返回消息
			writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream())), true);
			String s;
			while ((s = reader.readLine()) != null) {
				System.out.println(Thread.currentThread().getId() + " : " + s);
				// 返回消息
				writer.println("The server receive message is " + s);
				writer.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				reader.close();
				writer.close();
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}